﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using yy.Common;

namespace yy.options.sqlcmd
{
    /// <summary>
    /// 
    /// </summary>
    public class BaseOption : OptionI
    {
        /// <summary>
        /// 
        /// </summary>
        public BaseOption()
        {
            InitLog4netConfig();
        }

        /// <summary>
        /// 
        /// </summary>
        private Log4Helper Log4netHelper { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public virtual void OnExecute()
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="action"></param>
        public void Exec(string msg, Action action)
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                SendMsg($"{msg} error：{ex.Message}");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        public void SendMsg(string msg)
        {
            Console.WriteLine(msg);
            LogInfo(msg);
        }

        /// <summary>
        /// 
        /// </summary>
        public void InitLog4netConfig()
        {
            try
            {
                if (this.Log4netHelper != null)
                {
                    return;
                }

                string config = string.Empty;

                bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

                if (isWindows)
                {
                    config = AppDomain.CurrentDomain.BaseDirectory + "Config/log4net.config";
                }
                else
                {
                    config = AppDomain.CurrentDomain.BaseDirectory + "Config/log4net.unix.config";
                }

                this.Log4netHelper = Log4Helper.GetInstance(this.GetType(), config);
            }
            catch (Exception ex)
            {
                throw new Exception("初始化log4net配置信息发生错误，错误原因：" + ex.Message);
            }
        }

        /// <summary>
        /// 日志信息
        /// </summary>
        /// <param name="msg"></param>
        public void LogInfo(object message)
        {
            this.Log4netHelper?.Log.Info(message);
        }

        /// <summary>
        /// 调试信息
        /// </summary>
        /// <param name="message"></param>
        public void LogDebug(object message)
        {
            this.Log4netHelper.Log.Debug(message);
        }

        /// <summary>
        /// 错误信息
        /// </summary>
        /// <param name="message"></param>
        public void LogError(object message)
        {
            this.Log4netHelper?.Log.Error(message);
        }
    }
}